package cn.jluzh.blog.modules.comment.controller;

import cn.jluzh.blog.commons.result.Result;
import cn.jluzh.blog.commons.result.ResultFactory;
import cn.jluzh.blog.modules.article.entity.SysArticle;
import cn.jluzh.blog.modules.article.service.impl.ArticleServiceImpl;
import cn.jluzh.blog.modules.comment.dto.AuthorDto;
import cn.jluzh.blog.modules.comment.dto.ChildCommentDto;
import cn.jluzh.blog.modules.comment.entity.SysComment;
import cn.jluzh.blog.modules.comment.service.impl.CommentServiceImpl;
import cn.jluzh.blog.modules.comment.vo.SysCommentVo;
import cn.jluzh.blog.modules.security.eneity.SecurityUser;
import cn.jluzh.blog.modules.user.entity.SysUser;
import cn.jluzh.blog.modules.user.service.impl.UserServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: hjc
 **/

@RestController
@Api(tags = "评论相关接口")
@RequestMapping("comment")
public class CommentController {
    @Autowired
    CommentServiceImpl commentService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    ArticleServiceImpl articleService;
    /**
     * 获取某篇文章的评论
     */
    @GetMapping("/getCommentByArtId")
    @ApiOperation("获取某篇文章的评论")
    public Result info(@RequestParam("id") Long id) {
        List<SysCommentVo> sysCommentVos = commentService.queryArticleComments(id);
        JSONArray array = new JSONArray();
        for (SysCommentVo vo : sysCommentVos) {
            JSONObject object = formatCommentInfo(vo);
            QueryWrapper<SysComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id", vo.getArticleId());
            queryWrapper.eq("parent_id", vo.getId());
            int childCount = commentService.count(queryWrapper);
            if (childCount <= 0) {
                object.put("childrens", new JSONArray());
            } else {
                List<SysCommentVo> commentVoList = commentService.queryChildrenComments(new ChildCommentDto(vo.getArticleId(), vo.getId()));
                object.put("childrens", formatChildCommentInfo(commentVoList));
            }
            array.add(object);
        }

        return ResultFactory.buildSuccessResult(array);
    }

    /**
     * 发表评论
     */
    @PostMapping("/publishComment")
    public Result publishComment(@RequestBody JSONObject json) {
       SysUser sysUser = SecurityUser.getUser();

        Long articleId = json.getJSONObject("article").getLong("id");
        SysArticle sysArticle = articleService.getById(articleId);
        if (sysArticle == null) {
            throw new RuntimeException("参数有误");
        }
        JSONObject object = commentService.publishArticleComment(sysArticle, sysUser, json);

        return ResultFactory.buildSuccessResult(object);
    }


    /**
     * 删除
     */
    @GetMapping("/deleteComment")
    public Result deleteComment(@RequestParam("id") Long id) {
        Integer total=commentService.getDeleteTotalById(id);
        SysComment comment = commentService.getById(id);
        SysArticle article = articleService.getById(comment.getArticleId());
        article.setCommentNum(article.getCommentNum()-total);
        articleService.updateById(article);
        boolean b=commentService.deleteComments(id);
        return ResultFactory.buildSuccessResult(b);
    }
    /**
     * 格式化评论数据
     *
     * @param vo
     * @return
     */
    private JSONObject formatCommentInfo(SysCommentVo vo) {
        JSONObject object = new JSONObject();
        object.put("id", vo.getId());
        object.put("level", vo.getLevelFlag());
        object.put("content", vo.getContent());
        object.put("createDate", new DateTime(vo.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
        object.put("author", new AuthorDto(vo.getUserId(), vo.getAvatarName(), vo.getNickname()));
        return object;
    }

    /**
     * 获取子评论信息
     *
     * @param commentVoList
     * @return
     */
    private JSONArray formatChildCommentInfo(List<SysCommentVo> commentVoList) {
        JSONArray array = new JSONArray();
        for (SysCommentVo vo : commentVoList) {
            JSONObject object = formatCommentInfo(vo);
            object.put("childrens", new JSONArray());
            if (vo.getToUid() != null) {
                SysUser sysUser = userService.getById(vo.getToUid());
                object.put("toUser", new AuthorDto(sysUser.getId(), sysUser.getAvatarName(), sysUser.getNickname()));
            }
            array.add(object);
        }
        return array;
    }
}
